package cn.zn.framework.factory;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.zn.base.common.constant.Constants;
import cn.zn.base.common.utils.RequestContextUtil;
import cn.zn.base.common.utils.SpringContextUtil;
import cn.zn.log.entity.SysLoginRecord;
import cn.zn.log.entity.SysOperateLog;
import cn.zn.log.service.SysLoginRecordService;
import cn.zn.log.service.SysOperateLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 *
 * @author zn-admin
 */
public class OperateLogFactory {

    private static final Logger logger = LoggerFactory.getLogger("sys-user");

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLogin(final String loginname, final String username, final String status, final String message, final Object... args) {
        HttpServletRequest request = RequestContextUtil.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(ServletUtil.getHeaderIgnoreCase(request, "User-Agent"));
        final String ip = ServletUtil.getClientIP(request);
        return new TimerTask() {
            @Override
            public void run() {
                StringBuilder s = new StringBuilder();
                s.append(getBlock(ip));
                s.append(getBlock(loginname));
                s.append(getBlock(username));
                s.append(getBlock(status));
                s.append(getBlock(message));
                // 打印信息到日志
                logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOs().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLoginRecord loginRecord = new SysLoginRecord();
                loginRecord.setLoginName(loginname);
                loginRecord.setUserName(username);
                loginRecord.setIpAddress(ip);
                loginRecord.setBrowser(browser);
                loginRecord.setOs(os);
                loginRecord.setMsg(message);
                // 日志状态
                if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
                    loginRecord.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    loginRecord.setStatus(Constants.FAIL);
                }
                loginRecord.setLoginTime(new Date());
                loginRecord.setCreateBy(loginname);
                loginRecord.setCreateTime(new Date());
                loginRecord.setModifyBy(loginname);
                loginRecord.setModifyTime(new Date());
                // 插入数据
                SpringContextUtil.getBean(SysLoginRecordService.class).insertLoginRecord(loginRecord);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operateLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOperate(final SysOperateLog operateLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                SpringContextUtil.getBean(SysOperateLogService.class).insertOperateLog(operateLog);
            }
        };
    }

    /**
     * 处理并记录日志文件
     *
     * @param msg 内容
     * @return 结果
     */
    private static String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }
}

